package vip.xiaonuo.common.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

public class SignTool {

    /**
     * 加密
     *
     * @param jsonStr
     * @param token
     * @return
     */
    public static String signMd5Hex16(String jsonStr, String token) {
        String str = jsonStr + token;
        return DigestUtil.md5Hex16(str).toUpperCase();
    }

    /**
     * 验签
     *
     * @param params
     * @param token
     * @return
     */
    public static boolean verifyMd5Hex16(JSONObject params, String token) {
        JSONObject copied = params.clone();
        Object sign = copied.remove("sign");
        return ObjectUtil.equal(sign.toString().toUpperCase(), signMd5Hex16(copied.toJSONString().trim(), token));
    }

    /**
     * 加密
     *
     * @param jsonStr
     * @param token
     * @return
     */
    public static String signMd5Hex(String jsonStr, String token) {
        String str = jsonStr + token;
        return DigestUtil.md5Hex(str).toLowerCase();
    }

    /**
     * 验签
     *
     * @param params
     * @param token
     * @return
     */
    public static boolean verifyMd5Hex(String params, String token) {
        String str = StringUtils.substringBefore(params, "&sign=");
        String sign = StringUtils.substringAfter(params, "&sign=");
        return ObjectUtil.equal(sign.toLowerCase(), signMd5Hex(str, token));
    }
}
